import React, { useState, useEffect } from 'react';
import { 
  Box, 
  Typography, 
  Paper, 
  Button, 
  IconButton,
  LinearProgress,
  Grid,
  Card,
  CardContent,
  Chip,
  Divider,
  useTheme,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Stack,
  Alert,
  Snackbar,
  CircularProgress,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
} from '@mui/material';
import { 
  ArrowBack as ArrowBackIcon,
  CloudUpload as UploadIcon,
  Description as FileIcon,
  Check as CheckIcon,
  UploadFile as UploadFileIcon,
  Delete as DeleteIcon,
  Folder as FolderIcon,
  Error as ErrorIcon,
  Info as InfoIcon,
  FilePresent as FileDataIcon,
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { data as dataApi } from '../services/api';
import { useUser } from '../contexts/UserContext';

// 上传文件类型
const ALLOWED_EXTENSIONS = ['jsonl', 'csv'];

// 上传记录接口
interface UploadRecord {
  id: number;
  original_file_name: string;
  file_size: number;
  file_type: string;
  upload_time: string;
  status: 'processing' | 'completed' | 'failed';
  error_message?: string;
  summary_count: number;
}

const DataUpload: React.FC = () => {
  const [files, setFiles] = useState<File[]>([]);
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [uploadedRecords, setUploadedRecords] = useState<UploadRecord[]>([]);
  const [loadingRecords, setLoadingRecords] = useState(true);
  const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' as 'success' | 'error' | 'info' });
  const [fileError, setFileError] = useState('');
  const [selectedRecord, setSelectedRecord] = useState<UploadRecord | null>(null);
  const [detailsDialogOpen, setDetailsDialogOpen] = useState(false);
  
  const navigate = useNavigate();
  const theme = useTheme();
  const { currentUser } = useUser();

  // 加载上传历史
  useEffect(() => {
    loadUploadRecords();
  }, []);

  const loadUploadRecords = async () => {
    try {
      setLoadingRecords(true);
      const response = await dataApi.getUploads();
      setUploadedRecords(response.data);
    } catch (error) {
      console.error('加载上传记录失败:', error);
      setSnackbar({
        open: true,
        message: '加载上传历史失败',
        severity: 'error'
      });
    } finally {
      setLoadingRecords(false);
    }
  };

  const validateFile = (file: File): boolean => {
    // 检查文件类型
    const extension = file.name.split('.').pop()?.toLowerCase() || '';
    if (!ALLOWED_EXTENSIONS.includes(extension)) {
      setFileError(`不支持的文件类型: ${extension}，仅支持 ${ALLOWED_EXTENSIONS.join(', ')}`);
      return false;
    }

    // 检查文件大小 (限制为50MB)
    if (file.size > 50 * 1024 * 1024) {
      setFileError('文件大小超过50MB限制');
      return false;
    }

    setFileError('');
    return true;
  };

  const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files.length > 0) {
      const file = event.target.files[0];
      if (validateFile(file)) {
        setFiles([file]);
      } else {
        // 清空文件选择
        event.target.value = '';
      }
    }
  };

  const handleRemoveFile = (index: number) => {
    setFiles(files.filter((_, i) => i !== index));
    setFileError('');
  };

  const handleUpload = async () => {
    if (files.length === 0) return;

    setUploading(true);
    setUploadProgress(0);
    
    try {
      // 创建进度定时器模拟进度
      const progressInterval = setInterval(() => {
        setUploadProgress(prev => {
          if (prev >= 95) {
            clearInterval(progressInterval);
            return 95;
          }
          return prev + 5;
        });
      }, 200);

      // 上传文件
      const response = await dataApi.uploadFile(files[0]);
      
      clearInterval(progressInterval);
      setUploadProgress(100);
      
      // 显示成功消息
      setSnackbar({
        open: true,
        message: `上传成功，已处理 ${response.data.summary_count} 条摘要数据`,
        severity: 'success'
      });
      
      // 清空选择的文件
      setFiles([]);
      
      // 刷新上传记录
      loadUploadRecords();
    } catch (error: any) {
      console.error('上传失败:', error);
      setSnackbar({
        open: true,
        message: error.response?.data?.error || '上传失败，请稍后重试',
        severity: 'error'
      });
    } finally {
      setUploading(false);
    }
  };

  const getFileSize = (size: number) => {
    if (size < 1024) {
      return size + ' B';
    } else if (size < 1024 * 1024) {
      return (size / 1024).toFixed(2) + ' KB';
    } else {
      return (size / (1024 * 1024)).toFixed(2) + ' MB';
    }
  };

  const getFileTypeChip = (fileType: string) => {
    switch(fileType.toLowerCase()) {
      case 'jsonl':
        return <Chip size="small" label="JSONL" color="primary" />;
      case 'csv':
        return <Chip size="small" label="CSV" color="success" />;
      default:
        return <Chip size="small" label={fileType.toUpperCase()} color="default" />;
    }
  };

  const getStatusChip = (status: string) => {
    switch(status) {
      case 'completed':
        return <Chip size="small" label="完成" color="success" icon={<CheckIcon />} />;
      case 'processing':
        return <Chip size="small" label="处理中" color="warning" icon={<CircularProgress size={12} />} />;
      case 'failed':
        return <Chip size="small" label="失败" color="error" icon={<ErrorIcon />} />;
      default:
        return <Chip size="small" label={status} color="default" />;
    }
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const handleViewDetails = (record: UploadRecord) => {
    setSelectedRecord(record);
    setDetailsDialogOpen(true);
  };

  const handleCloseSnackbar = () => {
    setSnackbar(prev => ({ ...prev, open: false }));
  };

  return (
    <Box sx={{ p: 3, maxWidth: 1200, margin: '0 auto' }}>
      <Box sx={{ display: 'flex', alignItems: 'center', mb: 4 }}>
        <IconButton onClick={() => navigate('/chat')} sx={{ mr: 2 }}>
          <ArrowBackIcon />
        </IconButton>
        <Typography variant="h5" component="h1">
          数据上传
        </Typography>
      </Box>

      <Grid container spacing={3}>
        <Grid item xs={12} md={6}>
          <Paper sx={{ p: 3, height: '100%' }}>
            <Typography variant="h6" gutterBottom>
              上传文件
            </Typography>
            <Divider sx={{ mb: 3 }} />
            
            {fileError && (
              <Alert severity="error" sx={{ mb: 2 }}>
                {fileError}
              </Alert>
            )}
            
            <Box 
              sx={{ 
                border: `2px dashed ${theme.palette.divider}`,
                borderRadius: 2,
                p: 5,
                textAlign: 'center',
                mb: 3,
                bgcolor: theme.palette.background.default
              }}
            >
              <input
                type="file"
                accept={ALLOWED_EXTENSIONS.map(ext => `.${ext}`).join(',')}
                id="file-upload"
                style={{ display: 'none' }}
                onChange={handleFileChange}
                disabled={uploading}
              />
              <label htmlFor="file-upload">
                <Button
                  component="span"
                  variant="contained"
                  startIcon={<UploadFileIcon />}
                  sx={{ mb: 2 }}
                  disabled={uploading}
                >
                  选择文件
                </Button>
              </label>
              <Typography variant="body2" color="textSecondary">
                仅支持 JSONL 和 CSV 格式文件<br />
                文件大小不超过50MB
              </Typography>
              <Box sx={{ mt: 2 }}>
                <Tooltip title="文件格式说明">
                  <IconButton
                    onClick={() => setSnackbar({
                      open: true,
                      message: '每行必须包含JSON对象，包括fname(可选)、dialogue(必须)和summary(必须)字段',
                      severity: 'info'
                    })}
                  >
                    <InfoIcon color="info" />
                  </IconButton>
                </Tooltip>
              </Box>
              <UploadIcon sx={{ fontSize: 60, color: 'text.disabled', mt: 2 }} />
            </Box>

            {files.length > 0 && (
              <>
                <Typography variant="subtitle1" gutterBottom>
                  待上传文件
                </Typography>
                <List>
                  {files.map((file, index) => (
                    <ListItem
                      key={index}
                      secondaryAction={
                        <IconButton 
                          edge="end" 
                          onClick={() => handleRemoveFile(index)}
                          size="small"
                          disabled={uploading}
                        >
                          <DeleteIcon fontSize="small" />
                        </IconButton>
                      }
                    >
                      <ListItemIcon>
                        <FileIcon />
                      </ListItemIcon>
                      <ListItemText 
                        primary={file.name} 
                        secondary={getFileSize(file.size)} 
                        primaryTypographyProps={{ noWrap: true }}
                      />
                      {getFileTypeChip(file.name.split('.').pop()?.toLowerCase() || '')}
                    </ListItem>
                  ))}
                </List>

                {uploading ? (
                  <Box sx={{ mt: 2 }}>
                    <LinearProgress variant="determinate" value={uploadProgress} sx={{ mb: 1 }} />
                    <Typography variant="caption" color="textSecondary">
                      上传中 {uploadProgress}%
                    </Typography>
                  </Box>
                ) : (
                  <Button
                    variant="contained"
                    color="primary"
                    startIcon={<UploadIcon />}
                    onClick={handleUpload}
                    sx={{ mt: 2 }}
                    fullWidth
                  >
                    开始上传
                  </Button>
                )}
              </>
            )}
          </Paper>
        </Grid>

        <Grid item xs={12} md={6}>
          <Paper sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom>
              上传历史
            </Typography>
            <Divider sx={{ mb: 3 }} />

            {loadingRecords ? (
              <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}>
                <CircularProgress />
              </Box>
            ) : uploadedRecords.length === 0 ? (
              <Box sx={{ textAlign: 'center', py: 8 }}>
                <FolderIcon sx={{ fontSize: 60, color: 'text.disabled', mb: 2 }} />
                <Typography color="textSecondary">
                  暂无上传历史
                </Typography>
              </Box>
            ) : (
              <TableContainer>
                <Table>
                  <TableHead>
                    <TableRow>
                      <TableCell>文件名</TableCell>
                      <TableCell align="center">类型</TableCell>
                      <TableCell align="center">状态</TableCell>
                      <TableCell align="center">摘要数</TableCell>
                      <TableCell align="right">操作</TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {uploadedRecords.map((record) => (
                      <TableRow key={record.id}>
                        <TableCell>
                          <Typography variant="body2" noWrap sx={{ maxWidth: 150 }}>
                            {record.original_file_name}
                          </Typography>
                          <Typography variant="caption" color="textSecondary">
                            {formatDate(record.upload_time)}
                          </Typography>
                        </TableCell>
                        <TableCell align="center">
                          {getFileTypeChip(record.file_type)}
                        </TableCell>
                        <TableCell align="center">
                          {getStatusChip(record.status)}
                        </TableCell>
                        <TableCell align="center">
                          {record.summary_count}
                        </TableCell>
                        <TableCell align="right">
                          <Tooltip title="查看详情">
                            <IconButton 
                              size="small" 
                              onClick={() => handleViewDetails(record)}
                            >
                              <FileDataIcon fontSize="small" />
                            </IconButton>
                          </Tooltip>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            )}
          </Paper>
        </Grid>
      </Grid>

      {/* 上传记录详情对话框 */}
      <Dialog 
        open={detailsDialogOpen} 
        onClose={() => setDetailsDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        {selectedRecord && (
          <>
            <DialogTitle>
              上传详情 - {selectedRecord.original_file_name}
            </DialogTitle>
            <DialogContent>
              <Grid container spacing={2} sx={{ mb: 2 }}>
                <Grid item xs={6} md={3}>
                  <Typography variant="body2" color="textSecondary">上传时间</Typography>
                  <Typography variant="body1">{formatDate(selectedRecord.upload_time)}</Typography>
                </Grid>
                <Grid item xs={6} md={3}>
                  <Typography variant="body2" color="textSecondary">文件大小</Typography>
                  <Typography variant="body1">{getFileSize(selectedRecord.file_size)}</Typography>
                </Grid>
                <Grid item xs={6} md={3}>
                  <Typography variant="body2" color="textSecondary">文件类型</Typography>
                  <Typography variant="body1">{selectedRecord.file_type.toUpperCase()}</Typography>
                </Grid>
                <Grid item xs={6} md={3}>
                  <Typography variant="body2" color="textSecondary">状态</Typography>
                  <Typography variant="body1">{getStatusChip(selectedRecord.status)}</Typography>
                </Grid>
              </Grid>
              
              {selectedRecord.status === 'failed' && selectedRecord.error_message && (
                <Alert severity="error" sx={{ mb: 2 }}>
                  {selectedRecord.error_message}
                </Alert>
              )}
              
              <Typography variant="subtitle1" gutterBottom>
                处理结果
              </Typography>
              <Typography variant="body1">
                共处理 {selectedRecord.summary_count} 条摘要数据
              </Typography>
              
              <Box sx={{ mt: 2 }}>
                <Typography variant="caption" color="textSecondary">
                  您可以在摘要查询页面查看和搜索上传的摘要数据
                </Typography>
              </Box>
            </DialogContent>
            <DialogActions>
              <Button onClick={() => setDetailsDialogOpen(false)}>关闭</Button>
              {selectedRecord.status === 'completed' && (
                <Button 
                  variant="contained" 
                  onClick={() => {
                    setDetailsDialogOpen(false);
                    navigate('/summary-search');
                  }}
                >
                  查看摘要
                </Button>
              )}
            </DialogActions>
          </>
        )}
      </Dialog>

      {/* 全局提示 */}
      <Snackbar
        open={snackbar.open}
        autoHideDuration={6000}
        onClose={handleCloseSnackbar}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert 
          onClose={handleCloseSnackbar} 
          severity={snackbar.severity}
          variant="filled"
        >
          {snackbar.message}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default DataUpload; 